<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 活动模型
 * @author www.dingwei.cn
 */

class MerchantMessageModel extends MY_Model{
    public $tbMessage = 'merchant_message';
    public $tbMessageViewed = 'merchant_message_viewed';
    public $tbUser = 'merchant';

    // 送货订单提示
    public $TIPS = array(
        '1'=>'',
        '2'=>'请及时发货',
        '3'=>'',
        '4'=>'订单已被用户签收',
        '5'=>'',
        '6'=>'',
        '7'=>'',
        '8'=>'',
    );
    // 到店订单提示
    public $STORE_TIPS = array(
        '1'=>'',
        '2'=>'',
        '3'=>'到店展示二维码核销',
        '4'=>'订单核销成功',
        '5'=>'',
        '6'=>'',
        '7'=>'',
        '8'=>'',
    );
    /**
     * 后台获取数据列表
     * @return array
     * @author heyu
     */
    public function adminPcGetList(){
        $title = trim(get('title'));
        $type = (int)get('type');
        $star = strtotime(get('star'));
        $end = strtotime(get('end'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if($title){
            $this->db->like(array('title' => $title));
        }
        if ($type){
            $this->db->where(array('type' => $type));
        }
        if($star){
            $this->db->where('addtime >=', $star);
        }
        if($end){
            $this->db->where('addtime <= ', strtotime('+1day', $end));
        }
        if ($iSortCol_0 == 3){
            $this->db->order_by('addtime', $sSortDir_0);
        }else{
            $this->db->order_by('addtime', 'desc');
        }

        $this->db->select('id,type,title,content,addtime,count(addtime) as total')
            ->group_by('addtime');
        return $this->pagination($this->tbMessage);
    }

    /**
     * 保存信息
     * @param	array	$data	保存数据
     * @param	integer $id		消息id
     * @param	integer $orderId 订单id
     * @param	integer $saleId 售后订单id
     * @return	boolean
     * @author heyu
     */
    public function save($data, $id = 0, $orderId = 0, $saleId = 0){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('id' => $id));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }elseif($orderId){
            $this->db->where(array('order_id' => $orderId, 'type' => 3));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }elseif($orderId){
            $this->db->where(array('order_id' => $saleId, 'type' => 4));
            if($this->update($this->tbMessage, $data)){
                return true;
            }
        }
        else{
            if($id = $this->insert($this->tbMessage, $data)){
                return $id;
            }
        }
    }
    
    /**
     * 批量保存信息
     * @param	array	$data	保存数据
     * @param	integer $id		用户id
     * @return	boolean
     * @author heyu
     */
    public function saveBatch($data, $id = 0, $key = ''){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('id' => $id));
            if($this->updateBatch($this->tbMessage, $data)){
                return true;
            }
        }elseif ($key == 'order_id'){
            return $this->updateBatch($this->tbMessage, $data, 'order_id');
        }else{
            if($id = $this->insertBatch($this->tbMessage, $data)){
                return $id;
            }
        }
    }

    /**
     * 保存查看记录信息
     * @param	array	$data	保存数据
     * @return	boolean
     * @author heyu
     */
    public function saveView($data, $id = 0){

        if( ! $data) return false;
        if($id){
            $this->db->where(array('message_id' => $id));
            if($this->update($this->tbMessageViewed, $data)){
                return true;
            }
        }else{
            if($id = $this->insert($this->tbMessageViewed, $data)){
                return $id;
            }
        }

    }

    /**
     * 删除查看记录
     * @param $merchantId
     * @param $messageId
     * @return bool
     */
    public function deleteView($merchantId, $messageId = 0, $orderId = 0){
        if (!$orderId && !$messageId){
            return false;
        }
        if($messageId){
            $this->db->where(array('message_id' => $messageId));
        }
        if($orderId){
            $this->db->where(array('order_id' => $orderId));
        }
        $this->db->where(array('merchant_id' => $merchantId));
        return $this->delete($this->tbMessageViewed);
    }

    /**
     * 批量保存
     * @param $data
     * @return bool
     * @author heyu
     */
    public function batchSave($data){
        return $this->insertBatch($this->tbMessage, $data);
    }

    /**
     * 获取消息推送的人
     * @author heyu
     */
    public function getMerchantDetail(){
        $addTime = (int)get('addtime');
        if (!$addTime) return false;
        $nickname = get('nickname');
        $mobile = get('mobile');
        if ($nickname){
            $this->db->like(array('nickname' => $nickname));
        }
        if ($mobile){
            $this->db->like(array('mobile' => $mobile));
        }
        $this->db->select('u.portrait,u.nickname,u.mobile')
            ->join($this->tbUser.' u', 'm.merchant_id=u.id')
            ->where('m.addtime', $addTime);
        return $this->pagination($this->tbMessage.' m');
    }

    /**
     * 获取消息记录
     * @param $merchantId   商户id
     * @param $type  1：系统消息(所有人)  2：系统消息（指定人）  3：订单消息
     * @param $page
     * @return array
     * @author khj
     */
    public function appGetMessageList($merchantId, $type, $page){
        if(!$merchantId) return array();

        if($type == 3){ //订单消息
            $this->db->where_in('m.type', array(3,4));
            $this->db->where('m.merchant_id', $merchantId);
        }

        if($type == 1){//系统消息

            $this->db->where('m.type in(1,2) and m.id not in(select message_id from '.$this->tbMessageViewed.' 
                              where merchant_id = '.$merchantId.' and is_delete = 2) and (m.merchant_id = 0 
                              or m.merchant_id = '.$merchantId.')
                              and m.addtime > (select addtime from '.$this->tbUser.' where id = '.$merchantId.')');
        }
        get_instance()->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
        $this->db->select('m.id,m.title,m.type,m.content,m.order_id,m.addtime,v.message_id as viewed,
                        o.code,o.status,o.reality_amount,o.addtime as time,o.expense_type,os.status as service_status,
                        os.refund_amount,os.addtime as service_time,os.code as service_code')
                 ->join($this->tbUser.' u', 'u.id = m.merchant_id', 'left')
                 ->join($this->tbMessageViewed.' v', 'v.message_id = m.id ', 'left')
                 ->join($this->mOrder->tbOrder.' o','o.id = m.order_id and m.type = 3','LEFT')
                 ->join($this->mOrder->tbOrderService.' os','os.id = m.order_id and m.type = 4','LEFT')
                 ->group_by('m.id')
                 ->order_by('m.addtime desc')
                 ->where('(v.is_delete is null or v.is_delete = 1)');

        $tA = $this->appPage($this->tbMessage.' m', $page);
//p($this->db->last_query());
        foreach ($tA['list'] as $k=>$v){
            //是否查看过该消息
            $tA['list'][$k]['viewed'] = ! $v['viewed'] ? '1' : '2';
            $tA['list'][$k]['order_id'] = $v['order_id'] ? $v['order_id'] : '0';
            $tA['list'][$k]['addtime'] = date('m-d H:i:s', $v['addtime']);
            if($v['status']){//订单
                if ($v['expense_type'] == 1){
                    $tA['list'][$k]['status'] = $this->mOrder->STATUS[$v['status']];
                    $tA['list'][$k]['tips']  = $this->TIPS[$v['status']];
                }elseif ($v['expense_type'] == 2){
                    $tA['list'][$k]['status']  = $this->mOrder->STORE_STATUS[$v['status']];
                    $tA['list'][$k]['tips']  = $this->STORE_TIPS[$v['status']];
                }
                $tA['list'][$k]['amount']  = $v['reality_amount'];
                $tA['list'][$k]['time']  = dateFormat($v['time'], true);
            }
            if($v['service_status']){//售后单
                $tA['list'][$k]['status']  = $this->mOrder->SERVICE_TYPE[$v['service_status']];
                $tA['list'][$k]['tips']  = $v['content'];
                $tA['list'][$k]['amount']  = $v['refund_amount'];
                $tA['list'][$k]['code']  = $v['service_code'];
                $tA['list'][$k]['time']  = dateFormat($v['service_time'], true);
            }
            unset($tA['list'][$k]['service_status'],$tA['list'][$k]['expense_type'],$tA['list'][$k]['reality_amount'],
                $tA['list'][$k]['refund_amount'],$tA['list'][$k]['service_time'],$tA['list'][$k]['service_code']);
        }

        return $tA;
    }

    /**
     * 消息详情
     * @param $id   消息id
     * @param $merchantId 商户id
     * @param $orderId 订单id
     * @param $serviceId 售后id
     * @return array
     */
    public function getInfo($id, $merchantId = 0, $orderId = 0, $serviceId = 0){
        if(!$id && !$orderId && !$serviceId)return array();

        if($merchantId){
            $this->db->where('m.merchant_id', $merchantId);
        }
        if($orderId){
            $this->db->where(array('m.order_id' => $orderId, 'm.type' => 3));
        }
        if($serviceId){
            $this->db->where(array('m.order_id' => $serviceId, 'm.type' => 4));
        }

        if($id){
            $this->db->where('m.id', $id);
        }
        $this->db->select('m.id,m.order_id,m.title,m.type,m.content,m.content_detail,m.addtime,v.message_id as viewed')
                 ->join($this->tbMessageViewed.' v', 'v.message_id = m.id', 'left');

        $tA = $this->getOne($this->tbMessage.' m');
        if ($tA) {
            $tA['viewed'] = isset($tA['viewed']) ? '2' : '1'; //1未读 2已读
            $tA['content_detail'] = $tA['content_detail']?str_replace('{base_url}', base_url(), $tA['content_detail']):'';
        }
        return $tA;
    }

    /**
     * 删除消息
     * @param 	integer $id
     * @param 	int 	$merchantId
     * @return	boolean
     */
    public function deleteMessage($id = 0, $merchantId = 0, $orderId = 0){
        if(!$id && !$orderId)return false;
        if($id){
            $this->db->where(array('id' => $id));
        }

        if($orderId){
            $this->db->where(array('order_id' => $orderId));
        }

        if($merchantId){
            $this->db->where(array('merchant_id' => $merchantId));
        }
        return $this->delete($this->tbMessage);
    }

    /**
     * 获取消息数量
     * @param $merchantId   商家id
     * @return array
     */
    public function getMessageNumber($merchantId){
        $data = array('order' => '0', 'system' => '0', 'total' => '0');
        if (!$merchantId){
            return $data;
        }

        $this->db->select('count(if(m.type = 1, m.id, null)) as sTotal,
                            count(if(m.type = 2, m.id, null)) as aTotal,
                            count(if(m.type = 3, m.id, null)) as orderTotal,
                            count(if(m.type = 4, m.id, null)) as saleTotal,
                            m.type')
            ->join($this->tbMessageViewed.' v', 'v.message_id = m.id', 'left')
            ->where('m.merchant_id', $merchantId)
            ->where('(v.message_id is null or v.message_id = 1)')
            ->or_where('m.merchant_id=0')
            ->group_by('m.id');
        $tA = $this->getAll($this->tbMessage.' m');

        if (!empty($tA)){
            foreach ($tA as $k => $v){
                if ($v['type'] == 1 || $v['type'] == 2){
                    $data['system'] += $v['sTotal']+$v['aTotal'];
                }else if($v['type'] == 3 || $v['type'] == 4){
                    $data['order'] += $v['orderTotal'] + $v['saleTotal'];
                }
            }
            $data['total'] = ($data['order'] + $data['system']).'';
            $data['system'] = $data['system'].'';
            $data['order'] = $data['order'].'';

        }
        return $data;
    }

    /**
     * 消息类型
     * @param $key
     * @return mixed|string
     */
    public function getType($key = 0){
        $config = array(
            1 => '系统消息(所有人)',
            2 => '系统消息（指定人）',
            3 => '订单消息',
            4 => '售后订单消息',
        );
        if( ! $key){
            return $config;
        }
        return $config[$key];
    }
}